﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
namespace Topro.Application.Impl
{
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Enum;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Command;
    using Topro.Entity.Response.Command;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 指令业务接口实现
    /// </summary>
    public class CommandServiceImpl: CommandService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public CommandServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        #region 查询
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<CommandQueryResponse> CommandQuery(CommandQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "t.Id,t.OrderType,t.ResourceId,t.OrderId,t.From,t.To,t.Remark,t.CreateTime";
            var tableName = "t_command t";
            var orderby = "ORDER BY t.CreateTime DESC";
            var where = "where 1=1";

            #region 条件
            if (query.OrderType.HasValue)
            {
                where += string.Format(" And t.OrderType ={0}", query.OrderType.Value);
            }
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<CommandQueryResponse>();

                return new DataGrid<CommandQueryResponse>()
                {
                    Rows = list,
                    Total = count
                };
            }
        }
        #endregion

        #region 保存、修改
        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult Save(CommandSaveRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            var command = new Command()
            {
                OrderType = (int)OrderType.台车,
                From = request.From,
                To = request.To,
                Status = (int)CommandStatus.待操作,
                Info = "",
                DisplayOrder = 50,
                Remark = request.Remark,
                CreatedBy = request.UserId,
                CreateTime = DateTime.Now
            };

            //新增
            var commandId = _db.DbConnection.Insert<Command>(command);
            if (commandId <= 0)
            {
                throw new Exception("操作失败.");
            }

            response.Success = true;
            response.Message = "台车创建成功.";

            return response;
        }
        #endregion
    }
}
